import { Injectable, UnauthorizedException, Logger } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { UsersService } from '../users/users.service';
import { LoginDto } from './dto/login.dto';
import * as bcrypt from 'bcryptjs';

@Injectable()
export class AuthService {
  private readonly logger = new Logger(AuthService.name);

  constructor(
    private usersService: UsersService,
    private jwtService: JwtService,
  ) {}

  async validateUser(username: string, password: string): Promise<any> {
    this.logger.log(`开始验证用户: ${username}`);
    
    const user = await this.usersService.findByUsername(username);
    
    if (!user) {
      this.logger.warn(`用户不存在: ${username}`);
      return null;
    }
    
    this.logger.log(`找到用户: ${username}, ID: ${user.id}, 角色: ${user.role}`);
    
    const isPasswordValid = await bcrypt.compare(password, user.password);
    this.logger.log(`密码验证结果: ${isPasswordValid}`);
    
    if (isPasswordValid) {
      const { password, ...result } = user;
      this.logger.log(`用户验证成功: ${username}`);
      return result;
    }
    
    this.logger.warn(`密码验证失败: ${username}`);
    return null;
  }

  async login(loginDto: LoginDto) {
    this.logger.log(`收到登录请求: ${JSON.stringify(loginDto)}`);
    
    const user = await this.validateUser(loginDto.username, loginDto.password);
    
    if (!user) {
      this.logger.error(`登录失败: 用户名或密码错误 - ${loginDto.username}`);
      throw new UnauthorizedException('用户名或密码错误');
    }

    if (!user.isActive) {
      this.logger.error(`登录失败: 用户账户已被禁用 - ${loginDto.username}`);
      throw new UnauthorizedException('用户账户已被禁用');
    }

    this.logger.log(`用户登录成功: ${loginDto.username}, 开始更新最后登录时间`);

    // 更新最后登录时间
    await this.usersService.updateLastLogin(user.id);

    const payload = { 
      username: user.username, 
      sub: user.id,
      role: user.role 
    };

    this.logger.log(`生成JWT payload: ${JSON.stringify(payload)}`);

    const token = this.jwtService.sign(payload);
    this.logger.log(`JWT token生成成功，长度: ${token.length}`);

    return {
      access_token: token,
      user: {
        id: user.id,
        username: user.username,
        email: user.email,
        nickname: user.nickname,
        role: user.role,
        isActive: user.isActive,
        lastLoginAt: user.lastLoginAt
      }
    };
  }
}
